import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:base_flutter/base_flutter.dart';
import 'package:ble_measure_plugin/connect_devices_utils.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/scheduler.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/a_yyt/page/medical_check_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/permission/permission_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/event_bus.dart' as e;
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/base_dialog.dart';
import 'package:ls_work/widgets/function_grid_widget.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:ls_work/widgets/my_refresh_divider_list.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pc300_health_sdk/health_data_plugin.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:ble_measure_plugin/ble_measure_plugin.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../model/building_model.dart';
import '../../model/drop_data_model.dart';
import '../../ui/pc300_test_page.dart';
import '../../ui/select_old_page.dart';
import '../../widgets/drop_item_widget.dart';
import '../models/floor_list_entity.dart';

class MedicalPackageArea extends StatefulWidget {
  // final int serviceAreaId;

  MedicalPackageArea({
    Key? key,
    // this.serviceAreaId,
  });

  @override
  _MedicalPackageAreaState createState() => _MedicalPackageAreaState();
}

class _MedicalPackageAreaState extends State<MedicalPackageArea> {
  TextEditingController _controller = TextEditingController();
  int _page = 1;
  List<MedicalElderInfo> dataList = [];
  bool isMore = false;
  bool isUpSort = false;

  ///蓝牙是否开启
  bool isOnBluetooth = false;
  bool _isOnConnectDevice = false;

  BluetoothDevice? device;

  var buildingModel = BuildingModel();

  GZXDropdownMenuController _dropdownMenuController =
  GZXDropdownMenuController();

  RefreshController controller = RefreshController();

  @override
  void dispose() {
    if(Platform.isAndroid){
      HealthDataSdk.disConnect();
      HealthDeviceLinkUtils.isOnline = false;
      if(_deviceListener!=null){
        ConnectDeviceUtils.removeListener(_deviceListener!);
      }
    }

    // ConnectDeviceUtils.release();
    super.dispose();
  }

  OnDeviceStateListener? _deviceListener;
  String buildingId = '';
  String floorId = '';

  GlobalKey _stackKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    _deviceListener = (event) {
      if (event.hasLink) {
        Toast.cancelToast();
      }
      setState(() {
        _isOnConnectDevice = HealthDeviceLinkUtils.isOnline || event.hasLink;
      });
    };
    ConnectDeviceUtils.initMeasureDevice();
    ConnectDeviceUtils.addOnDeviceStateListener(_deviceListener!);


    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
     _getBuildingData();
    });

    e.eventBus.on("deviceOff", (arg) {
      setState(() {
        _isOnConnectDevice = HealthDeviceLinkUtils.isOnline ||
            ConnectDeviceUtils.stateModel.hasLink;
      });
    });
  }

  Future<void> initPlatformState() async {
    try {
      isOnBluetooth = await HealthDataSdk.isOpen();
      if (isOnBluetooth) {
        // _searchToast();
      }
    } on PlatformException {}

    if (!mounted) return;
  }


  List<FloorEntity> buildingList = [];
  FloorEntity? selectBuilding;
  List<FloorInfo> floorList = [];
  FloorInfo? selectFloor;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            GZXDropDownHeader(
              // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
              items: [
                GZXDropDownHeaderItem(selectBuilding?.buildingNo??"全部"),
                GZXDropDownHeaderItem(selectFloor?.floorNo??"全部"),

              ],
              // GZXDropDownHeader对应第一父级Stack的key
              stackKey: _stackKey,
              // controller用于控制menu的显示或隐藏
              controller: _dropdownMenuController,
              height: 50,
              color: Colours.bg_color,
              borderColor: Colours.bg_color,
              dividerHeight: 20,
              dividerColor: Colours.order_line,
              style: TextStyle(color: Color(0xFF666666), fontSize: 14),
              dropDownStyle: TextStyle(
                fontSize: 14,
                color: Colours.app_main,
              ),
              iconDropDownColor: Colours.app_main,
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 80.0,
                  padding: EdgeInsets.fromLTRB(15, 20, 15, 20),
                  color: Colours.bg_gray,
                  child: Localizations(
                    locale: const Locale("en", ""),
                    delegates: [
                      GlobalMaterialLocalizations.delegate,
                      GlobalWidgetsLocalizations.delegate,
                      GlobalCupertinoLocalizations.delegate,
                    ],
                    child: TextField(
                      key: const Key('srarch_text_field'),
                      style: TextStyles.textDark16,
                      autofocus: false,
                      controller: _controller,
                      maxLines: 1,
                      onSubmitted: (value) {
                        _onRefresh();
                      },
                      onChanged: (str){
                        if(str.isNullOrEmpty()){
                          _onRefresh();
                        }
                      },
                      textInputAction: TextInputAction.search,
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.only(
                            top: 6.0, left: 15.0, right: -20.0, bottom: 6.0),
                        fillColor: Colors.white,
                        filled: true,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none,
                        ),
                        hintText: '输入姓名/房号',
                        hintStyle: TextStyles.textGrayC14,
                        suffixIcon: InkWell(
                          child: Padding(
                            padding: const EdgeInsets.only(
                                left: 16.0, top: 8.0, bottom: 8.0),
                            child: const LoadAssetImage("order_delete"),
                          ),
                          onTap: () {
                            /// https://github.com/flutter/flutter/issues/35909
                            SchedulerBinding.instance.addPostFrameCallback((_) {
                              _controller.text = "";
                              _onRefresh();
                            });
                          },
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Expanded(
              child: dataList.length <= 0
                  ? Gaps.emptyContainer
                  :SmartRefresher(controller: controller,
              child: createScrollWidget(),onRefresh: _onRefresh,onLoading: _loadMore,enablePullUp: true,).addToContainer(
                color: Colours.bg_color
              )
            ),
          ],
        ),

        // 下拉菜单
        GZXDropDownMenu(
          // controller用于控制menu的显示或隐藏
          controller: _dropdownMenuController,
          // 下拉菜单显示或隐藏动画时长
          animationMilliseconds: 300,
          dropdownMenuChanging: (isShow, index) {

          },
          dropdownMenuChanged: (isShow, index) {

          },
          menus: [
            GZXDropdownMenuBuilder(
              dropDownHeight: min(40.0 * buildingList.length,
                  MediaQuery
                      .of(context)
                      .size
                      .height * 0.75),
              dropDownWidget: buildConditionListWidget(buildingList, (data) {
                _dropdownMenuController.hide();
                setState(() {
                  selectBuilding = data as FloorEntity?;
                  setFloor();
                });
                _onRefresh();
              }),
            ),
            GZXDropdownMenuBuilder(
              dropDownHeight: min(40.0 * floorList.length,
                  MediaQuery
                      .of(context)
                      .size
                      .height * 0.75),
              dropDownWidget:
              buildConditionListWidget(floorList, (value) {
                _dropdownMenuController.hide();
                setState(() {
                  selectFloor = value as FloorInfo?;
                });
                _onRefresh();
              }),
            ),
          ],
        ),

      ],
      key: _stackKey,
    );
  }



  Future<void> _getBuildingData() async {
    try{
      var list = await buildingModel.getBuildingList(rows: 100);
      setState(() {
        buildingList = list;
        selectBuilding = list[0];
        selectBuilding?.iSelected = true;
        setFloor();
      });
      _fectData();

    }catch(e){
      Toast.show(NetErrorUtils.getNetError(e));
    }
  }

  void setFloor(){
    if(selectBuilding!=null){
      floorList = selectBuilding!.floorList??[];
      if(floorList.first.floorNo=="全部"){
        var first = floorList.first;
        first.iSelected = true;
        selectFloor = first;
      }else{
        var first = FloorInfo(
          floorNo: "全部",
        );
        first.iSelected = true;
        floorList.insert(0, first);
        selectFloor = first;
      }
    }
  }

  Widget createScrollWidget() {
    var ori = MediaQuery.of(context).orientation;
    return SingleChildScrollView(
      child: FunctionGridColumn(
        children: List.generate(dataList.length, (index){
          var item = dataList[index];
          return newOldContent(item).onTap(() async {
            var isBluetoothOpen = await HealthDataSdk.isOpen();
            if(!isBluetoothOpen){
              if(await PermissionRequest.isLackPermission(Permission.bluetoothScan)){
                var status = await Permission.bluetoothScan.status;
                print(status);
                if(status.isDenied){
                  PermissionRequest.requestPermissions([Permission.bluetoothScan,Permission.bluetoothConnect,Permission.bluetooth]);
                }else{
                  PermissionRequest.requestPermissions([Permission.bluetoothScan,Permission.bluetoothConnect,Permission.bluetooth]);
                }
              }else{
                showToast("请打开蓝牙");
              }
              return;
            }
            ConnectDeviceUtils.initMeasureDevice();
            showCupertinoDialog(context: context, builder: (context){
              return CupertinoAlertDialog(
                content: Text('是否需要连接PC304健康测量包',style: TextStyle(
                    fontSize: 16
                ),textAlign: TextAlign.center,),
                actions: [
                  TextButton(onPressed: (){
                    Navigator.pop(context);
                    toMeasurePage(index,false);
                  }, child: Text("否",style: TextStyle(color: Colors.red),)),
                  TextButton(onPressed: (){
                    Navigator.pop(context);
                    toMeasurePage(index,true);
                  }, child: Text("是")),
                ],
              );
            });
          });
        }),
        mainSpace: 10,
        crossSpace: 10,
        count: ori==Orientation.portrait?3:6,
      ),
      padding: EdgeInsets.symmetric(horizontal: 16),
    );
  }

  _fectData() async {
    var map = {
      'page': _page,
      'rows': 20,

      // 'serviceAreaId': widget.serviceAreaId,
      'customerNameOrRoomNoLike': _controller.text,
      'orderBy': 'room_no',
      'orderByDesc': isUpSort, //不传或为false时是正序，传true时是倒序
      'isLive': '1'
    };
    if(!(selectBuilding?.iId??"").isNullOrEmpty()){
      map['buildingId'] = selectBuilding?.iId??"";
    }
    if(!(selectFloor?.iId??"").isNullOrEmpty()){
      map['floorId'] = selectFloor?.iId??"";
    }

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.customerElder}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            MedicalElderModel model = MedicalElderModel.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = ((model.rows??[]).length == 20);
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              if (_page == 1) {
                /// 刷新
                setState(() {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                });
              }
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
          initPlatformState();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectData();
    controller.refreshCompleted();
  }

  Future _loadMore() async {
    _page++;
    await _fectData();
    controller.loadComplete();
  }

  void toMeasurePage(int index,bool needPc304) {
    AppNavigator.push(
      context,
      MedicalCheckPage(
        info: dataList[index],
        isOnConnectDevice: _isOnConnectDevice,
        needPc304: needPc304,
        callBack: (isConnectDevice) {
          if (mounted) {
            setState(() {
              _isOnConnectDevice = isConnectDevice;
            });
          }
        },
      ),
    );
  }
}
